import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import type { RequestType, MethodType } from '@/utils/http/types'
import { requestResponse } from '@/utils/errorPrompt'

class Request {
  service: AxiosInstance
  constructor(API: string, TIMEOUT: number) {
    this.service = axios.create({
      baseURL: API,
      timeout: TIMEOUT,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;form-data;json;' }
    })
    this.service.interceptors.request.use(this.__request, this.__requestError)
    this.service.interceptors.response.use(this.__response, this.__responseError)
  }
  // 请求拦截器
  __request(config: InternalAxiosRequestConfig) {
    // console.log('config: ', config)
    return config
  }
  // 请求拦截器错误
  __requestError(error: Promise<Error>) {
    return Promise.reject(error)
  }
  // 响应拦截器
  __response(response: AxiosResponse) {
    requestResponse(response.status)
    // console.log('response: ', response)
    return response.data
  }
  // 响应拦截器错误
  __responseError(error: Promise<Error>) {
    return Promise.reject(error)
  }
  // 返回请求数据
  request<T>(
    method: MethodType,
    api: string,
    data?: { data?: Object; params?: Object }
  ): Promise<T> {
    const requestData: RequestType<MethodType> = {
      url: api,
      method: method,
      ...data
    }
    return this.service(requestData)
  }
}

export const http = new Request(
  import.meta.env.VITE_APP_BASE_API,
  import.meta.env.VITE_APP_BASE_TIMEOUT
)
